<script setup lang="ts">
import { ref } from 'vue'
import { timeFormat, toYuan, timeFormat_2 } from '@/hooks/util'
import * as fansApi from '@/api/fans'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'
import EditRemark from './components/EditRemark.vue'
import EditBalance from './components/EditBalance.vue'
import SearchDrawer from '@/components/search-drawer/Index.vue'
import Blacklist from './components/Blacklist.vue'
import dayjs from 'dayjs'
import moment from 'moment'

const searchDrawerRef = ref()

const editRemarkRef = ref()
const EditBalanceRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const datesList = ref<[Dayjs, Dayjs]>([
  dayjs().subtract(29, 'days').startOf('day'),
  dayjs().endOf('day'),
])

import 'dayjs/locale/zh-cn'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
// 将选择范围控制在7天
import type { Moment } from 'moment'
const dates = ref<Moment[]>([])

// 将选择范围控制在7天
const disabledDate1 = (current: Moment) => {
  if (!dates.value || dates.value.length === 0) {
    return false
  }
  const diffDate = current.diff(dates.value[0], 'days')
  return Math.abs(diffDate) > 29
}
const onCalendarChange1 = (val: Moment[]) => {
  dates.value = val
}
type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined
let startTime = ref<string>()
let endTime = ref<string>()
const changeTime1 = (e: RangeValue | [string, string], dataString: [string, string]) => {
  console.log(dataString)
  // startTime.value = dataString[0]
  // endTime.value = dataString[1]
  startTime.value = dataString[0]
  endTime.value = dataString[1]
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  robotId?: string
  city?: string
  nickName?: string
  remark?: string
  fansFishId?: string
  fishId?: string
  id?: string
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 100,
  },
  {
    title: '粉丝信息',
    key: 'nickName',
    width: 300,
  },
  {
    title: '平台信息',
    key: 'fishId',
    width: 300,
  },
  {
    title: '备注/城市',
    key: 'remark',
    width: 300,
  },
  {
    title: '时间信息',
    key: 'createTime',
    width: 300,
    fixed: 'right',
  },
  {
    title: '操作',
    key: 'operation',
    width: 150,
    fixed: 'right',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
const getList = async () => {
  searchParams.value.startTime = new Date(
    moment(datesList.value[0].$d).format('YYYY-MM-DD 00:00:00'),
  ).getTime()
  searchParams.value.endTime = new Date(
    moment(datesList.value[1].$d).format('YYYY-MM-DD 23:59:59'),
  ).getTime() //改为完整的时间
  loading.value = true
  try {
    let { state, data, message: msg } = await fansApi.getFishFansList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 拉取机器人列表
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'
const robatList = ref<SelectProps['options']>([])
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })

      if (data.list.length == 0) {
        message.error('闲鱼：无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: any) => {
  okRobat.value = selectValue as string
  searchParams.value.robotId = okRobat.value
  getList()
  getCityList(okRobat.value)
}

// 拉取城市列表
const cityList = ref<SelectProps['options']>([])
const getCityList = async (robotId: string) => {
  try {
    let { state, data, message: msg } = await fansApi.getFishFansCityList({ robotId })
    if (state === 200) {
      cityList.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

onMounted(() => {
  getRobatList()
})

// 查询
const formRef = ref()
interface FormState {
  city?: string
  nickName?: string
  remark?: string
  fansFishId?: string
  fishId?: string
  id?: string
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    searchParams.value.fansFishId = formState.fansFishId || ''
    searchParams.value.fishId = formState.fishId || ''
    searchParams.value.city = formState.city || ''
    searchParams.value.id = formState.id || ''

    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')
  Reflect.deleteProperty(searchParams.value, 'fansId')
  Reflect.deleteProperty(searchParams.value, 'fishId')
  Reflect.deleteProperty(searchParams.value, 'city')
  Reflect.deleteProperty(searchParams.value, 'id')

  getList()
}

// 备注
const editRemark = async (id: string, remark: string) => {
  let params = { id, remark }
  try {
    const { state, message: msg } = await fansApi.editFishFansRemark(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const open = ref(false)
const BlacklistRef = ref()

/** 点击上传公共黑名单按钮 */
const addPublicBlacklist = (val: any) => {
  // console.log('点击上传公共黑名单按钮')
  open.value = true

  setTimeout(() => {
    BlacklistRef.value.onMoFailed(val)
  }, 0)
}

// 点击确定
const handleOk = () => {
  BlacklistRef.value.onOk()
}

const refreshTu = () => {
  open.value = false
}

// 余额
const editBalance = (record: any) => {
  EditBalanceRef.value.showModal(record)
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

const advancedSearch = () => {
  searchDrawerRef.value.showDrawer()
}
</script>

<template>
  <div style="margin: 5px 0; text-align: right">
    <span>选择闲鱼账号：</span>
    <a-select v-model:value="okRobat" @change="selectRobat" placeholder="请选择" style="width: 200px; text-align: left"
      show-search :options="optionList" :filter-option="filterOption">
      <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
  </div>

  <div class="searchBox">
    <a-form ref="formRef" layout="inline" :model="formState">
      <a-form-item label="昵称" name="nickName">
        <a-input v-model:value="formState.nickName" placeholder="昵称" style="width: 200px" />
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formState.remark" placeholder="备注" style="width: 200px" />
      </a-form-item>

      <a-form-item label="粉丝ID" name="fansFishId">
        <a-input v-model:value="formState.id" placeholder="粉丝ID" style="width: 200px" />
      </a-form-item>

      <a-form-item label="时间段" name="time1">
        <a-range-picker style="height: 32px; line-height: 35px; width: 250px" v-model:value="datesList"
          :disabledDate="disabledDate1" @calendarChange="onCalendarChange1" :locale="locale"
          :placeholder="['开始日期', '结束日期']" @change="changeTime1" />
      </a-form-item>

      <SearchDrawer ref="searchDrawerRef">
        <div>
          <a-form-item label="昵称" name="nickName">
            <a-input v-model:value="formState.nickName" placeholder="昵称" style="width: 285px" />
          </a-form-item>

          <a-form-item label="备注" name="remark">
            <a-input v-model:value="formState.remark" placeholder="备注" style="width: 285px" />
          </a-form-item>

          <a-form-item label="城市" name="city">
            <a-select v-model:value="formState.city" placeholder="请选择" allowClear style="width: 285px">
              <a-select-option v-for="(item, index) in cityList" :key="index" :value="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="粉丝ID" name="fansFishId">
            <a-input v-model:value="formState.id" placeholder="粉丝ID" style="width: 245px" />
          </a-form-item>

          <a-form-item label="平台账号闲鱼ID" name="fishId">
            <a-input v-model:value="formState.fishId" placeholder="平台账号闲鱼ID" style="width: 218px" />
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset" style="margin-left: 10px">重置</a-button>
          </a-form-item>
        </div>
      </SearchDrawer>
    </a-form>
    <a-button type="primary" @click="search">搜索</a-button>
    <a-button @click="reset">重置</a-button>
    <a-button type="primary" @click="advancedSearch">高级搜索</a-button>
  </div>

  <a-alert description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格" type="info" banner
    style="margin-bottom: 10px; padding: 10px" />

  <a-table style="overflow-x: scroll" :columns="columns" :data-source="dataSource" :pagination="pagination"
    :loading="loading" @change="changePage" rowKey="id" size="small" :scroll="{ x: 100 }">
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'avatar'">
        <div style="text-align: center">
          <span>头像</span>
        </div>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'avatar'">
        <div class="imgBox">
          <img :src="record.avatar" alt="" />
        </div>
      </template>

      <template v-else-if="column.key === 'createTime'">
        <a-descriptions bordered size="small" :column="1">
          <a-descriptions-item label="创建时间">
            {{ timeFormat_2(record.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ timeFormat_2(record.updateTime) }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'nickName'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '90px' }">
          <a-descriptions-item label="昵称">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.nickName }}</span>
              </template>
              <span class="hiddenText">{{ record.nickName }}</span>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="会员名">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.memberName }}</span>
              </template>
              <span class="hiddenText">{{ record.memberName }}</span>
            </a-tooltip>
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'remark'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
          <a-descriptions-item label="备注">
            <div style="display: flex; align-items: center">
              <a-tooltip placement="top" v-if="!record.isRemarkShow">
                <template #title>
                  <span>{{ record.remark }}</span>
                </template>
                <span class="hiddenText">{{ record.remark }}</span>
              </a-tooltip>
              <a-input v-else v-model:value="record.remark" @blur="editRemark(record.id, record.remark)"
                style="border: 0" />
              <EditOutlined @click="EditRemarkSet(record)" v-if="!record.isRemarkShow"
                style="margin-left: 6px; color: #1890ff" />
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="城市">
            {{ record.city }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'fishId'">
        <a-descriptions bordered size="small" :column="1">
          <a-descriptions-item label="粉丝闲鱼ID">
            {{ record.fansFishId }}
          </a-descriptions-item>
          <a-descriptions-item label="平台账号闲鱼ID">{{ record.fishId }}</a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-if="column.key === 'operation'">
        <a-button type="text" style="color: #1890ff" @click="addPublicBlacklist(record)">
          上传公共黑名单
        </a-button>
      </template>
    </template>
  </a-table>

  <EditRemark ref="editRemarkRef" @refresh="getList"></EditRemark>
  <EditBalance ref="EditBalanceRef" @refresh="getList"></EditBalance>

  <a-modal v-model:open="open" :maskClosable="false" centered title="上传公共黑名单" @ok="handleOk">
    <div>
      <Blacklist @refreshTu="refreshTu" ref="BlacklistRef"></Blacklist>
    </div>
  </a-modal>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  border-radius: 50%;
  overflow: hidden;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;

  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
